package com.ogawa.joypal.user.viewmodel

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.ogawa.base.base.BaseViewModel
import com.ogawa.base.bean.LoadState
import com.ogawa.projectcommon.utils.dataConvert
import com.ogawa.projectcommon.utils.launch
import com.ogawa.projectcommon.network.RetrofitManager
import com.ogawa.joypal.user.bean.*
import com.ogawa.joypal.user.service.UserApiService
import com.ogawa.projectcommon.constants.Constant
import kotlinx.coroutines.cancel

class UserInfoRegisterViewModel : BaseViewModel() {
    var mPutUserInfoRequest = PutUserInfoRequest()
    var requestUserBean = MutableLiveData<PutUserInfosResponse>()
    var putUserInfoState = MutableLiveData<String>()
    var mUserInfosBean = MutableLiveData<UserInfosBean>()
    init {
        mPutUserInfoRequest = PutUserInfoRequest()
    }

    fun putUserInfo() {
        launch({
            loadState.value = LoadState.Loading("")
            requestUserBean.value = RetrofitManager.INSTANCE.createService(UserApiService::class.java)
                .putUserInfo(mPutUserInfoRequest)
                .dataConvert()
            loadState.value = LoadState.Success("")
            putUserInfoState.value = Constant.SUCCESS
        }
            , { loadState.value = LoadState.Fail(it.message ?: "") }
            , {})
    }


    fun  userInfo(id:String){
        launch({
            loadState.value = LoadState.Loading("")

            mUserInfosBean.value = RetrofitManager.INSTANCE.createService(UserApiService::class.java)
                .userInfo(id)
                .dataConvert()
            loadState.value = LoadState.Success("")
        }
            , { loadState.value = LoadState.Fail(it.message ?: "") }
            , {})
    }



    //不需要，在ViewModel销毁时候会自己清除
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    open fun onDestroy() {
        LogUtils.e("onDestroy")
        viewModelScope.cancel()
    }


}
